<template>
  <div id="invite-assess-order">
    <div class="search-box">
        <el-form>
             <el-form-item label="店铺名称：">
                <el-select v-model="searchForm.shopId" placeholder="请选择店铺" size="small" filterable :filter-method="dataFilter" clearable>
                  <el-option v-for="(item, index) in shopNameList" :key="index" :label="item.name" :value="item.id"></el-option>
                </el-select>
             </el-form-item>
             <el-form-item label="计划ID：">
               <el-input placeholder="请输入计划ID" v-model="searchForm.planCode" size="small" clearable></el-input>
             </el-form-item>
             <el-form-item label="任务ID：">
               <el-input placeholder="请输入任务ID" v-model="searchForm.taskCode" size="small" clearable></el-input>
             </el-form-item>
             <el-form-item label="商品ID：">
               <el-input placeholder="请输入商品ID" v-model="searchForm.productId" size="small" clearable></el-input>
             </el-form-item>
             <el-form-item label="推手账号：">
               <el-input placeholder="请输入推手账号" v-model="searchForm.account" size="small" clearable></el-input>
             </el-form-item>
             <el-form-item label="付款金额：">
               <el-input placeholder="请输入付款金额" v-model="searchForm.payMoney" size="small" clearable></el-input>
             </el-form-item>
             <el-form-item label="订单号：">
               <el-input placeholder="请输入订单号" v-model="searchForm.orderNum" size="small" clearable></el-input>
             </el-form-item>
             <el-form-item label="完成时间 ：">
             <el-date-picker size="small" v-model="completeTime" type="datetimerange" @change="changeCompleteTime" :default-time="['00:00:00', '23:59:59']" range-separator="至" start-placeholder="开始日期"
             :picker-options="pickerOptions"  end-placeholder="结束日期"></el-date-picker>
             </el-form-item>
             <el-form-item label="审核时间 ：">
             <el-date-picker size="small" v-model="checkTime" type="datetimerange" @change="changeCheckTime" :default-time="['00:00:00', '23:59:59']" range-separator="至" start-placeholder="开始日期"
             :picker-options="pickerOptions"  end-placeholder="结束日期"></el-date-picker>
             </el-form-item>
            <el-form-item>
                <el-button class="search-btn" icon="el-icon-ali-search" @click="searchData">查&nbsp;询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button class="reset-btn" icon="el-icon-ali-reset" @click="resetSearchParam">重&nbsp;置</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div class="table-box">
      <div class="table-header-box">
        <el-button class="search-btn" icon="el-icon-ali-batch" @click="batchAssessDialog = true">批量邀请首评</el-button>

      </div>
      <el-table border :data="tableData" max-height="580px" @selection-change="tableSelectionChange">
        <el-table-column type="selection" width="55" :selectable="selectAble"></el-table-column>
        <el-table-column prop="platform_type" label="店铺类型/店铺名称">
          <div slot-scope="scope">
           <div class="textColor">{{getShopType(scope.row)}}</div>
           <div>{{scope.row.shop_name}}</div>
          </div>
        </el-table-column>
        <el-table-column width="120px" prop="goods_img" label="商品主图">
          <el-popover placement="right" trigger="hover" slot-scope="scope" v-if="scope.row.goods_img">
            <img class="goods-preview-img" :src="scope.row.goods_img"/>
            <img slot="reference" :src="scope.row.goods_img"  style="width: 80px;height: 80px">
          </el-popover>
        </el-table-column>
        <el-table-column prop="product_id" label="应付金额/商品ID">
          <div slot-scope="scope">
              <div class="textColor">{{scope.row.all_pay_money}}</div>
              <div>{{scope.row.product_id}}</div>
          </div>
        </el-table-column>
        <el-table-column prop="tb_name" label="推手账号/订单号">
          <div slot-scope="scope">
              <div class="textColor">{{scope.row.tb_name}}</div>
              <div style="color: #ee7b5a;">{{scope.row.order_num}}</div>
          </div>
        </el-table-column>
        <el-table-column prop="all_pay_money" label="实付金额/实付佣金">
          <div slot-scope="scope">
              <div class="textColor">{{scope.row.real_pay}}</div>
              <div style="color: #ee7b5a;">{{scope.row.all_commission}}</div>
          </div>
        </el-table-column>
        <el-table-column prop="over_time" label="完成时间/审核时间">
          <div slot-scope="scope">
            <div>{{scope.row.over_time}}</div>
            <div>{{scope.row.check_time}}</div>
          </div>
        </el-table-column>
        <el-table-column prop="plan_code" label="计划ID/任务ID">
         <div slot-scope="scope">
            <div class="planCodeStyle" @click="toPlanDetailPage(scope.row.plan_id)">{{scope.row.plan_code}}</div>
            <div>{{scope.row.task_code}}</div>
         </div>
        </el-table-column>
        <el-table-column label="操作"  fixed="right" width="130" class-name="shenghe">
          <template slot-scope="scope">
            <div class="assess-list-btn">
              <el-button class="assess-btn"  v-if="scope.row.assess_status_type == 2" size="mini" @click="assessOrder(scope.row,1)">邀请评价</el-button>
              <div v-if="scope.row.assess_status_type == 1">已邀请</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-table :data="allTableData" id = "exportTable" border v-show="false">
        <el-table-column prop="shop_type" label="店铺类型" :formatter="getShopType"></el-table-column>
        <el-table-column prop="shop_name" label="店铺名称"></el-table-column>
        <el-table-column prop="product_id" label="商品ID"></el-table-column>
        <el-table-column prop="entrance_type" label="入口类型" :formatter="getEntranceType"></el-table-column>
        <el-table-column prop="keyword" label="关键词">
          <div slot-scope="scope" v-if="scope.row.entrance_type == 1 || scope.row.entrance_type == 2">
            {{scope.row.keyword}}
          </div>
        </el-table-column>
        <el-table-column prop="tb_name" label="推手账号"></el-table-column>
        <el-table-column prop="all_pay_money" label="应付金额"></el-table-column>
        <el-table-column prop="real_pay" label="实付金额"></el-table-column>
        <el-table-column prop="order_num" label="订单号"></el-table-column>
        <el-table-column prop="all_commission" label="佣金"></el-table-column>
        <el-table-column prop="over_time" label="完成时间"></el-table-column>
        <el-table-column prop="check_time" label="审核时间"></el-table-column>
        <el-table-column prop="task_code" label="任务ID"></el-table-column>
        <el-table-column prop="plan_code" label="计划ID"></el-table-column>
      </el-table>
      <div class="table-footer">
        <el-button icon="el-icon-download" class="download-btn" @click="downloadExcel">导出</el-button>
        <el-pagination :page-sizes="[5, 10, 15, 20]" :page-size="searchForm.pageSize" :current-page="searchForm.page" layout="total, sizes, prev, pager, next, jumper"
          :total="pageToatal" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
      </div>
    </div>
    <v-assess :assessForm="assessForm" :createType="1" @closeDialog="closeAssessDialog" @confrimAssess="confrimAssess" v-if="showAssessDialog"></v-assess>
    <el-dialog title="提示" :visible.sync="batchAssessDialog" width="400px" class="dialog-style">
      <p>是否确定进行批量邀请首次评价操作?</p>
      <span slot="footer" class="dialog-footer">
        <el-button class="cancel-btn" @click="batchAssessDialog = false">取 消</el-button>
        <el-button class="submit-btn"  :loading="submitLoading" @click="batchAssessSuccess">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    apiGetMerchantShopList,
    apiSuccessCheckSaleTaskList,
    apiOnedragnGoods,
    apiBatchCreateAssessTask
  } from '../../request/api.js'
  import { mapGetters,mapActions } from 'vuex';
  import vAssess from '../../components/createAssess.vue'
  export default{
    components: {
       vAssess
    },
    data(){
      return {
        searchForm:{
          token: '',
          page: 1,
          pageSize: 10,
          shopId: '',
          productId: '',
          planCode: '',
          taskCode: '',
          startTime: '',
          endTime: '',
          account: '',
          payMoney: '',
          orderNum: '',
          checkEndTime: '',
          checkStartTime: '',
          shopType: ''
        },
        assessForm:{
          token: '',
          assessContent: '',
          imgUrls: '',
          videoUrl: '',
          id: '',
          pushId: '',
          platformType: '',
          assessType: '',
          selfType: 2
        },
        completeTime: [],
        checkTime: [],
        shopNameList: [],
        shopNameOptions: [],
        platformNameObject:{
          1: '淘宝',
          2: '天猫',
          3: '京东',
		  4: '1688',
          13: '唯品会',
          15: '拼多多'
        },
        entranceType: {
          1: '关键词',
          2: '淘口令',
          3: '二维码',
          4: '直播',
          5: '其他'
        },
        pageToatal: 0,
        tableData: [],
        pickerOptions: {
          disabledDate(time) {
             let merchantTime = window.localStorage.getItem('merchantTime')
             let curDate = (new Date()).getTime();
             let three = merchantTime * 24 * 3600 * 1000;
             let threeMonths = curDate - three;
             return time.getTime() < threeMonths;
          },
        },
        allTableData: [],
        platformTypeList: [{
          label: '淘宝',
          value: 1
        },{
          label: '天猫',
          value: 2
        },{
          label: '京东',
          value: 3
        },{
          label: '1688',
          value: 4
        },{
          label: '唯品会',
          value: 13
        },{
          label: '拼多多',
          value: 15
        }],
        otherShopType: [3,13],
        batchAssessDialog: false,
        batchAssess:{
          token: '',
          saleTaskIds: ''
        },
        batchIds: [],
        submitLoading: false,
        showAssessDialog: false,
        userToken: window.localStorage.getItem('token')
      }
    },
    created() {
      this.searchForm.token = this.userToken
      this.searchForm.shopType = this.platformType
      this.getCurTime()
      this.getShopList()
      this.getTableData()
    },
    computed:{
      ...mapGetters(['platformType']),
    },
    watch: {
      platformType: function (val) {
        this.searchForm.shopType = val
        this.getTableData()
      }
    },
    methods:{
       dataFilter(val) {
         this.searchForm.shopId = val;
         if (val) { //val存在
           this.shopNameList = this.shopNameOptions.filter((item) => {
             if (!!~item.name.indexOf(val) || !!~item.name.toUpperCase().indexOf(val.toUpperCase())) {
               return true
             }
           })
         } else { //val为空时，还原数组
           this.shopNameList = this.shopNameOptions;
         }
       },
       getShopList() {
         this.$isClick(true);
         apiGetMerchantShopList({
           token: this.userToken
         }).then(res =>{
           this.$isClick(false);
            if (res.code == 1){
             for (var i in res.msg.merchant_shop_list) {
               this.shopNameOptions.push({
                 name: this.platformNameObject[res.msg.merchant_shop_list[i].type] + '-' + res.msg.merchant_shop_list[i].name,
                 id: res.msg.merchant_shop_list[i].id
               })
             }
              this.shopNameList = this.shopNameOptions
            } else {
              this.$message.error(res.msg);
            }
         }).catch(res => {
           this.$isClick(false);
             this.$message.error(res.msg)
         })
       },
       getTableData(){
         this.$isClick(true);
          apiSuccessCheckSaleTaskList(this.searchForm).then(res =>{
            this.$isClick(false);
             if (res.code == 1){
              this.tableData = res.msg.res
              this.pageToatal = res.msg.allNum
             } else {
               this.$message.error(res.msg);
             }
          }).catch(res => {
            this.$isClick(false);
              this.$message.error(res.msg)
          })
       },
       selectAble(row){
         if (row.assess_status_type == 2) {
             return true
         } else {
           return false
         }
       },
       //批量
       tableSelectionChange(val) {
         this.batchIds = val.map(item => item.task_id);
       },
       batchAssessSuccess(){
         if (this.batchIds.length == 0) {
           this.$message.error('请先选择需要批量自评的订单');
           return
         }
         this.submitLoading = true
         this.batchAssess.token = this.userToken
         this.batchAssess.saleTaskIds = this.batchIds.join(',')
         apiBatchCreateAssessTask(this.batchAssess).then(res =>{
           this.submitLoading = false
            if (res.code == 1){
             this.$message.success(res.msg);
             this.batchAssessDialog = false
             this.batchIds = []
             this.getTableData()
            } else {
              this.$message.error(res.msg);
            }
         }).catch(res => {
            this.submitLoading = false
            this.$message.error(res.msg)
         })
       },
       assessOrder(row,type){
         this.assessForm = {
           token: this.userToken,
           assessContent: '',
           imgUrls: '',
           videoUrl: '',
           pushId: row.push_id,
           platformType: row.shop_type,
           id: row.task_id,
           assessType: type,
           selfType: 2
         }
         this.showAssessDialog = true
         // 处理非一拖N评价及追评功能
         if (row.is_onedragn != 1) {
           this.showAssessDialog = true
           return
         }
         // 处理一拖N评价及追评
         apiOnedragnGoods({
           token: this.userToken,
           task_code: row.task_code
         }).then(res => {
           if (res.code == 200) {
             this.$set(this.assessForm, "goodsInfo", res.data)
             this.$set(this.assessForm, "product_id", "")
             this.showAssessDialog = true
           } else {
             this.$message.error(res.msg)
           }
         }).catch(err => {})
       },
       closeAssessDialog(){
         this.showAssessDialog = false
       },
       confrimAssess(){
         this.$message.success('邀请成功');
         this.getTableData()
         this.showAssessDialog = false
       },
       getEntranceType(row){
         return this.entranceType[row.entrance_type]
       },
       getShopType(row){
         return this.platformNameObject[row.platform_type]
       },
       searchData(){
         this.searchForm.page = 1
         this.searchForm.pageSize = 10
         this.getTableData()
       },
       resetSearchParam(){
        this.searchForm = {
           token: this.userToken,
           page: 1,
           pageSize: 10,
           shopId: '',
           productId: '',
           planCode: '',
           taskCode: '',
           startTime: '',
           endTime: '',
           account: '',
           payMoney: '',
           orderNum: '',
           checkEndTime: '',
           checkStartTime: '',
           shopType: this.platformType
         }
       },
       getCurTime(){
         var now = new Date();
         var startTime = new Date(new Date().toLocaleDateString()).getTime() - 24 * 60 * 60 * 1000 * 6
         var endTime = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1;
         this.completeTime = [startTime,endTime]
         this.searchForm.startTime = Math.floor(startTime / 1000)
         this.searchForm.endTime =  Math.floor(endTime / 1000)
       },
       handleSizeChange(val) {
       	this.searchForm.pageSize = val;
       	this.getTableData()
       },
       handleCurrentChange(val) {
       	this.searchForm.page = val;
       	this.getTableData()
       },
       changeCheckTime(val){
         if (this.checkTime == null) {
           this.searchForm.checkStartTime =  ''
           this.searchForm.checkEndTime =  ''
         } else{
           this.dataDiff(val[0],val[1],'check')
           this.searchForm.checkStartTime =  this.changeTimeType(val[0])
           this.searchForm.checkEndTime =  this.changeTimeType(val[1])
         }
       },
       changeCompleteTime(val){
        if (this.completeTime == null) {
          this.searchForm.startTime =  ''
          this.searchForm.endTime =  ''
        } else{
          this.dataDiff(val[0],val[1],'success')
          this.searchForm.startTime =  this.changeTimeType(val[0])
          this.searchForm.endTime =  this.changeTimeType(val[1])
        }
       },
       dataDiff(startTime,endTime,type){
         let diff = endTime-startTime
         let t = 31*24*60*60*1000
         if(diff>t){
          this.$message.error('时间范围不能超过31天')
          if (type == 'success') {
            this.completeTime = []
          } else {
            this.checkTime = []
          }

           return false;
         }
       },
       changeTimeType(time){
         var d = new Date(time);
         var s = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
         return new Date(s).getTime() /1000;
       },
       toPlanDetailPage(id){
         this.$router.push("/plan/salesPlanDetail?id=" + id);
       },
       getAllTableData(){
         let data = JSON.parse(JSON.stringify(this.searchForm))
         data.page = 1
         data.pageSize = this.pageToatal
         if (data.pageSize == 0) {
            this.$message.error('当前表格没有数据可以导出');
            return
         }
         return new Promise ((resolve) =>{
           this.$isClick(true);
           apiSuccessCheckSaleTaskList(data).then(res =>{
             this.$isClick(false);
              if (res.code == 1){
                 this.allTableData = res.msg.res
                resolve(res) ;
              } else {
                this.$message.error(res.msg);
              }
           }).catch(res => {
             this.$isClick(false);
               this.$message.error(res.msg)
           })
         })

       },
       downloadExcel(){
         this.$loading.show('下载中')
         var wb = ''
          var xlsxParam = { raw: true }
          this.getAllTableData().then(()=>{
          wb = this.XLSX.utils.table_to_book(document.querySelector('#exportTable'),xlsxParam)
          var wbout = this.XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
          try {
            this.FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }),'销量已完成订单.xlsx')
          } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
          setTimeout(() => {
            this.$loading.hide()
            this.$message.success('下载完成')
          }, 1000);
          return wbout
         })
       }
    }
  }
</script>

<style lang="less">
  #invite-assess-order{
    .table-header-box {
      .search-btn {
        background: #f16f6f;
        color: #fff;
        padding: 8px 15px!important;
        margin-bottom: 10px;
      }
    }
    .assess-list-btn {
      .assess-btn {
        background: @themeColor;
        color: #fff;
        padding: 8px 15px!important;
        margin-bottom: 5px;
      }
    }
  }
  .el-popover {
    .goods-preview-img,.keyword-preview-img {
      width: 200px;
      height: 200px;
    }
  }
</style>
